package org.supda.system.controller.background;


import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.supda.system.annoation.SysLog;
import org.supda.system.controller.common.BaseController;
import org.supda.system.entity.TMessageSend;
import org.supda.system.entity.TResources;
import org.supda.system.entity.TUser;
import org.supda.system.service.ResourceService;
import org.supda.system.service.TMessageSendService;
import org.supda.system.service.UserService;
import org.supda.system.task.MessageCountScheduledTask;
import org.supda.system.task.MessageMapSingleton;
import org.supda.system.task.ScheduledTasks;

import com.octo.captcha.service.CaptchaService;

/**
 * 
 * @author supda
 * @Date 2016-12-24 下午4:37:18
 *
 */
@Controller
@RequestMapping("/")
public class BackgroundController extends BaseController{

	@Inject
	private UserService userService;
	
	@Inject
	private CaptchaService captchaService;
	
	@Inject
	private ResourceService resourceService;
	
	@Inject TMessageSendService messageSendService;
	
	@Inject private SimpMessageSendingOperations simpMessagingTemplate;
	
	@Inject private SimpMessageSendingOperations simpMessageSendingOperations;

	
	/**
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	public String login(HttpServletRequest request) {
		request.removeAttribute("error");
		//System.out.println("123");
		return "/login";
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "welcome", method = RequestMethod.GET ,  produces = "text/html; charset=utf-8")
	public String login() {
		return BASE_VIEW_PACKAGE+"welcome";
	}
	
	@SysLog(module="用户登录", method="login", desc="用户登录")
	@RequestMapping(value = "login", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
	public String login(String username, String password,String code, HttpServletRequest request,Model model) {
		
		model.addAttribute("username", username);
		model.addAttribute("code", code);
		
		//验证码判断
		Boolean isCorrect = Boolean.FALSE;  
		String captchaId = request.getSession().getId();  
		try {  
		    isCorrect = captchaService.validateResponseForID(captchaId,  
		            code);  
		    if (!isCorrect) {  
		    	request.setAttribute("error", "验证码有误，请重试！");
		        return "/login";  
		    }  
		} catch (Exception e) {  
			//e.printStackTrace();
		}  
		
		try {
			if (!request.getMethod().equals("POST")) {
				request.setAttribute("error", "支持POST方法提交！");
			}
			if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
				request.setAttribute("error", "用户名或密码不能为空！");
				return "/login";
			}
			// 想要得到 SecurityUtils.getSubject()　的对象．．访问地址必须跟ｓｈｉｒｏ的拦截地址内．不然后会报空指针
			Subject user = SecurityUtils.getSubject();
			// 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
			// 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
			// 当以上认证成功后会向下执行,认证失败会抛出异常
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			
			try {
				user.login(token);
			} catch (LockedAccountException lae) {
				token.clear();
				request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
				return "/login";
			} catch (ExcessiveAttemptsException e) {
				token.clear();
				request.setAttribute("error", "账号：" + username + " 登录失败次数过多,锁定10分钟!");
				return "/login";
			} catch (AuthenticationException e) {
				token.clear();
				request.setAttribute("error", "用户或密码不正确！");
				return "/login";
			}
			request.removeAttribute("error");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", "登录异常，请联系管理员！");
			return "/login";
		}
		return "redirect:index.shtml";
	}

	/**
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({"index","/"})
	public String index(Model model) throws Exception {
		
		//权宜
		if(ScheduledTasks.simpMessageSendingOperations == null || MessageCountScheduledTask.simpMessageSendingOperations == null) {
			ScheduledTasks.simpMessageSendingOperations = simpMessageSendingOperations;
			MessageCountScheduledTask.simpMessageSendingOperations = simpMessageSendingOperations;
		}
		
		// 获取登录的bean
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		TUser user =  (TUser) getSession().getAttribute("userSession");
		
		user = userService.findById(user.getId());

		Long root = 0L;
		
		 Set<TResources> resList = userService.findResources(user.getAccountName());
		
		 Map<TResources , List<TResources>> menuList =  resourceService.warpMenu(resList);
		 
		 //加载未读消息
		 
		model.addAttribute("msgCount", messageSendService.getMsgCount(user.getId())); 
		model.addAttribute("menuList", menuList);
		model.addAttribute("user",user);
		 
		return "/index";
	}

	@RequestMapping("menu")
	public String menu(Model model) {
		return "/framework/menu";
	}

	/**
	 * 获取某个用户的权限资源
	 */
	@RequestMapping("findAuthority")
	@ResponseBody
	public List<String> findAuthority(HttpServletRequest request) {
		return null;
	}
	
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	@SysLog(module="用户注销",method="logout",desc="用户退出")
	public String logout() {
		// 使用权限管理工具进行用户的退出，注销登录
		SecurityUtils.getSubject().logout(); // session
												// 会销毁，在SessionListener监听session销毁，清理权限缓存
		return "redirect:login.shtml";
	}
	
	@RequestMapping(value="notifyInfo")
	public String notifyInfo(HttpServletRequest request,
			Model model) {

		TUser user = (TUser)SecurityUtils.getSubject().getSession().getAttribute("userSession");
		
		if(user!=null){
			//历史消息
			List<TMessageSend> readedMessages = messageSendService.readedMessages(user.getId());
			
			//未读消息
			List<TMessageSend> unReadMessages = messageSendService.readMessages();
			
			model.addAttribute("unReadMessages", unReadMessages);
			model.addAttribute("readedMessages", readedMessages);
		}
		
		return BASE_VIEW_PACKAGE+"message";
	}
	
}
